package com.usabb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.usabb.pojo.vo.AmenityAddVO;
import org.springframework.stereotype.Service;

import com.usabb.dao.HospitalRelationDao;
import com.usabb.domain.HospitalRelationDO;
import com.usabb.service.HospitalRelationService;
import com.ifast.common.base.CoreServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 医院关联表
 * </pre>
 * <small> 2019-08-19 18:03:27 | Aron</small>
 */
@Service
public class HospitalRelationServiceImpl extends CoreServiceImpl<HospitalRelationDao, HospitalRelationDO> implements HospitalRelationService {

    @Override
    public List<HospitalRelationDO> getListBy(String bizType, Long bizId) {
        Wrapper<HospitalRelationDO> wrapper = generateDOWrapper(bizType, bizId);
        final List<HospitalRelationDO> relationDOS = this.selectList(wrapper);
        return relationDOS;
    }

    @Override
    public List<Long> getHospitalIdsBy(String bizType, Long bizId) {
        return getListBy(bizType, bizId)
                .stream().map(it->it.getHospitalId())
                .collect(Collectors.toList());
    }

    @Override
    public boolean saveOrUpdate(AmenityAddVO addVO) {
        return saveOrUpdate(addVO.getBizType(), addVO.getBaseId(), addVO.getHospitalId());
    }

    @Override
    public boolean saveOrUpdate(String bizType, Long baseId, Long[] hospitalIds) {
        deleteBy(bizType, baseId);
        return insert(bizType, baseId, hospitalIds);
    }

    private boolean insert(String bizType, Long baseId, Long[] hospitalIds) {
        List<HospitalRelationDO> list = new ArrayList<>(hospitalIds.length);
        for (Long hospitalId : hospitalIds) {
            HospitalRelationDO relationDO = new HospitalRelationDO();
            relationDO.setBizType(bizType);
            relationDO.setMaternityId(baseId);
            relationDO.setHospitalId(hospitalId);

            list.add(relationDO);
        }

        return this.insertBatch(list);
    }

    private boolean deleteBy(final String bizType, final Long baseId) {
        Wrapper<HospitalRelationDO> wrapper = generateDOWrapper(bizType, baseId);

        boolean delete = this.delete(wrapper);
        log.info("Deleted HospitalRelationDOs. baseId:{}, result:{}", baseId, delete);
        return delete;
    }

    private static Wrapper<HospitalRelationDO> generateDOWrapper(String bizType, Long baseId) {
        HospitalRelationDO param = new HospitalRelationDO();
        param.setBizType(bizType);
        param.setMaternityId(baseId);
        return new EntityWrapper<>(param);
    }


}
